﻿' ----------------------------------------------------------------------------------
' Microsoft Developer & Platform Evangelism
' 
' Copyright (c) Microsoft Corporation. All rights reserved.
' 
' THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES 
' OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
' ----------------------------------------------------------------------------------
' The example companies, organizations, products, domain names,
' e-mail addresses, logos, people, places, and events depicted
' herein are fictitious.  No association with any real company,
' organization, product, domain name, email address, logo, person,
' places, or events is intended or should be inferred.
' ----------------------------------------------------------------------------------

Imports Microsoft.Samples.WindowsPhoneCloud.StorageClient
Imports Microsoft.Samples.WindowsPhoneCloud.Phone.Models
Imports System.Windows.Threading
Imports System.Globalization

Namespace ViewModel

    Public Class SampleDataTablePageViewModel
        Inherits TableBaseViewModel(Of SampleData)
        Private Const IconsRootUri As String = "/Toolkit.Content/"
        Private ReadOnly cloudTableClientValue As ICloudTableClient

        Private Shared sampleDataTableCreated As Boolean = False

        Public Sub New()
            Me.New(App.CloudClientFactory, Deployment.Current.Dispatcher)
        End Sub

        Public Sub New(ByVal cloudClientFactory As ICloudClientFactory, ByVal dispatcher As Dispatcher)
            MyBase.New(cloudClientFactory, dispatcher)
            Me.cloudTableClientValue = cloudClientFactory.ResolveCloudTableClient(Me.TableName)
        End Sub

        Public Event Navigate As EventHandler(Of NavigationEventArgs)

        Public ReadOnly Property CloudTableClient() As ICloudTableClient
            Get
                Return Me.cloudTableClientValue
            End Get
        End Property

        Public Overrides ReadOnly Property TableName() As String
            Get
                Return "SampleData"
            End Get
        End Property

        Public Overrides Sub LoadTable()
            If Not sampleDataTableCreated Then
                Try
                    Me.CloudTableClient.CreateTableIfNotExist(Me.TableName, Sub(r)
                                                                                If Me.Dispatcher IsNot Nothing Then
                                                                                    Me.Dispatcher.BeginInvoke(Sub() Me.HandleTableCreationResponse(r))
                                                                                Else
                                                                                    Me.HandleTableCreationResponse(r)
                                                                                End If
                                                                            End Sub)
                Catch exception As Exception
                    Dim errorMessage = StorageClientExceptionParser.ParseDataServiceException(exception).Message

                    Me.IsLoading = False
                    Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", errorMessage)
                End Try
            Else
                MyBase.LoadTable()
            End If
        End Sub

        Public Sub NavigateTo(ByVal navigationUri As Uri)
            Me.RaiseNavigate(navigationUri)
        End Sub

        Protected Overrides Sub PopulateApplicationBarButtons(ByVal applicationBar As IApplicationBar)
            Dim refreshButton = New ApplicationBarIconButton(New Uri(String.Format("{0}{1}", IconsRootUri, "appbar.refresh.rest.png"), UriKind.Relative)) With {.Text = "refresh"}
            AddHandler refreshButton.Click, Sub(s, e) Me.LoadTable()

            Dim addButton = New ApplicationBarIconButton(New Uri(String.Format("{0}{1}", IconsRootUri, "appbar.add.rest.png"), UriKind.Relative)) With {.Text = "add row"}
            AddHandler addButton.Click, Sub(s, e) Me.RaiseNavigate(New Uri("/Pages/SampleDataDetailsPage.xaml?editSampleData=false", UriKind.Relative))

            applicationBar.Buttons.Add(refreshButton)
            applicationBar.Buttons.Add(addButton)
        End Sub

        Private Sub HandleTableCreationResponse(ByVal response As CloudOperationResponse(Of Boolean))
            If response.Exception Is Nothing Then
                MyBase.LoadTable()
                sampleDataTableCreated = True
            Else
                Me.Message = String.Format(CultureInfo.InvariantCulture, "Error: {0}", response.Exception.Message)
            End If
        End Sub

        Private Sub RaiseNavigate(ByVal uri As Uri)
            RaiseEvent Navigate(Me, New NavigationEventArgs(Nothing, uri))
        End Sub
    End Class
End Namespace